package controllers;

import org.json.JSONObject;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;

import beans.UserBean;
import dto.Dto;
import services.impl.UserServiceImpl;

public class UserController extends Controller{
	@Inject
	UserServiceImpl userService;

	public void index(){

	}

	@Clear
	public void login(){
		Dto dto = new Dto();
		JSONObject json = getRequestBody();
		if(json.has("userName")&&json.has("password")){
			String userName = json.getString("userName");
			String password = json.getString("password");
			dto = userService.login(userName, password);
		}else{
			dto.setErrMsg("Missing required field userName or password.");
		}
		renderJson(dto);
	}

	@Clear
	public void signup(){
		Dto dto = userService.signUp(getBean());
		renderJson(dto);
	}
	
	public void changePassword(){
		Dto dto = userService.changePassword(getBean());
		renderJson(dto);
	}
	
	public void updateProfile(){
		Dto dto = userService.updateProfile(getBean());
		renderJson(dto);
	}
	
	public void getProfile(){
		Dto dto = userService.getProfile(getBean());
		renderJson(dto);
	}
	
	private UserBean getBean(){
		String jsonStr = getRawData();
		UserBean bean = FastJson.getJson().parse(jsonStr, UserBean.class);
		if(bean==null){
			bean = new UserBean();
		}
		String userId = String.valueOf(getRequest().getAttribute("userId")) ;
		bean.setUserId(userId);
		return bean;
	}

	private JSONObject getRequestBody(){
		JSONObject json = new JSONObject();
		String jsonStr = getRawData();
		try{
			json = new JSONObject(jsonStr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return json;
	}
}
